#!/usr/bin/ruby
require "rubygems"
require "nokogiri"
require "open-uri"
require File.expand_path("../../album", __FILE__)

class RenrenAlbum < Album
  def initialize
    super
    @regex = /http:\/\/page.renren.com\/\w+\/album\/\d+/
    @verified_urls = []
  end
  
  def go
    time_start = Time.now
    begin
      verify_urls
      @verified_urls.each do |url|
        @current_url = url
        get_url_for_pics
        create_ablum_folder
        get_remote_pics
      end
    rescue NoValidUrlError, NoValidPicError => e
      puts e.class.to_s, e.message, e.backtrace
    end
    puts "Costing time: #{Time.now - time_start}"
  end
  
  protected
  
  def verify_urls
    @urls.each do |url|
      if @regex =~ url
        @verified_urls << url
      end
    end
    raise NoValidUrlError, "No url is valid! Please input corrent ones!" if @verified_urls.empty?
  end
  
  def get_url_for_pics
    puts "You are downloading renren pics from #{@current_url}"
    @doc = Nokogiri::HTML(open(@current_url))
    @folder_name = @current_url.scan(/album\/(\d+)/)[0].to_s + "_" + @doc.css("div.pager-top span h3").inner_text.to_s
    @sum = @doc.css("div.pager-top span").inner_text.to_s.scan(/共(\d+)张/)[0][0].to_i
    raise NoValidPicError, "This is an invalid ablum!" if @sum.nil?
    
    i, times, @image_urls = 0, @sum/15, []
    while i <= times do
      page = Nokogiri::HTML(open(@current_url+"?curpage="+i.to_s))
      page.css("td.photoPan a").each do |link|
        url = @current_url.scan(/http:\/\/[\w+\.]+/)[0].to_s + link.attribute("href").to_s
        @image_urls << open(url).read.scan(/"large":"(http:[\\\/\w.]+\.jpg)"/)[0][0].gsub(/\\/, "")
      end
      i += 1
    end
  end
    
  def get_remote_pics(use_threads=false)
    if use_threads
      puts "Downloading starts in multi-threads way."
      threads = []
    else
      puts "Downloading starts in normal way."
    end
    
    @image_urls.each_with_index do |img, i|
      regex = /p[\w+_]+\.jpg/
      dest = regex.match(img).to_s
      output_file = File.join(@folder_name, dest)
      if use_threads 
        threads << Thread.new do 
          stream = open(img) { |f| f.read }
          open(output_file, "wb") do |f|
            puts "creating file #{output_file} from #{@image_urls[i]} ... #{i+1}/#{@image_urls.count}"
            f.write(stream)
          end
        end
      else
        stream = open(img) { |f| f.read }
        open(output_file, "wb") do |f|
          puts "creating file #{output_file} from #{@image_urls[i]} ... #{i+1}/#{@image_urls.count}"
          f.write(stream)
        end
      end
    end
    
    if use_threads
      threads.each { |t| t.join }
    end
    puts "Downloading renren pics from #{@current_url} has completed!"
  end
  
end

RenrenAlbum.new.go